//
//  LZPersonInfoViewController.m
//  DoctorFAQs
//
//  Created by langZai on 2017/2/20.
//  Copyright © 2017年 zjq. All rights reserved.
//


typedef NS_ENUM(NSInteger,CellType){
    
    CellTypeWithDefualt = 0,
    CellTypeWithAge,
    CellTypeWithPhoneNumber
};

#import "LZPersonInfoViewController.h"
#import "LZPersonInfoTopCell.h"
#import "LZPersonInfoMidCell.h"
#import "LZPersonInfoBottomCell.h"
#import "LZChangPwdViewController.h"
#import "LZSelectView.h"
#import "JTTakeAlbumOrCamera.h"
#import "LZUserInfo.h"
#import "UIImage+RadiusAndColor.h"
#import "LZWriteNameCell.h"
#import "LZSelectSexView.h"
#import "LZWriteAgeCell.h"
#import "LPopChangView.h"
#import "LZChangPhoneVC.h"


@interface LZPersonInfoViewController ()<UITableViewDelegate,UITableViewDataSource,pointOutDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,selectSexDelegate> {

    LZUserInfo *userInfo;
}

/** tableView */
@property (nonatomic, strong) UITableView *mainTableView;
/** 内容数组 */
@property (nonatomic, strong) NSMutableArray *contentArray;
/** 标题数组 */
@property (nonatomic, strong) NSArray *titleArray;
// 选择头像View
@property (nonatomic,strong) LZSelectView *selectView;
/** 选择性别View */
@property (nonatomic, strong) LZSelectSexView *selectSexView;
/** 初始化中间cell的值 */
@property (nonatomic, strong) NSMutableArray *firstDataArr;


@end
static NSString *cellIDa = @"personInfoCella";
static NSString *cellIDb = @"personInfoCellb";
static NSString *cellIDc = @"personInfoCellc";
@implementation LZPersonInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    userInfo = [LZUserInfo getUserInfo];
//    NSLog( @"%@",[LZUserInfo shareInfo].uid);
    [self createTableView];
    self.navigationItem.title = @"个人资料";
    _titleArray = @[@"姓名",@"性别",@"年龄",@"手机号"];
//    _contentArray = [NSMutableArray array];
    _contentArray = [@[@"填写姓名",@"选择性别",@"填写年龄",@"15002807974"] mutableCopy];
    NSString *name = userInfo.userName ? userInfo.userName : @"";
    NSString *sex = userInfo.userSex ? userInfo.userSex : @"";
    NSString *age = userInfo.userAge ? userInfo.userAge : @"";
    NSString *phone = userInfo.phone ? userInfo.phone : @"";
    
    _firstDataArr = [@[name,sex,age,phone] mutableCopy];
    
}


// 创建tableView
- (void)createTableView {
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc] init];
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        //_mainTableView.userInteractionEnabled = NO;
        _mainTableView.backgroundColor = KHColorFromRGB(0xf8f8f8);
        [_mainTableView registerClass:[LZPersonInfoTopCell class] forCellReuseIdentifier:cellIDa];
        [_mainTableView registerClass:[LZPersonInfoMidCell class] forCellReuseIdentifier:cellIDb];
        [self.view addSubview:_mainTableView];
        
        [_mainTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.sizeOffset(CGSizeMake(SCREEN_Width, SCREEN_Height));
            make.centerX.equalTo(self.view);
            make.top.equalTo(self.view);
        }];
    }
    
    // 下拉刷新
    __weak typeof(self) weakSelf = self;
    _mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf yiQiShowNetWorking];
        [weakSelf.mainTableView.mj_header endRefreshing];
    }];
//    _mainTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
//        [weakSelf yiQiShowMoreNetWorking];
//        [weakSelf.mainTableView.mj_footer endRefreshing];
//    }];
    
    
    // 编辑按钮
//    UIButton *editBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60*xsIZE, 30*ysIZE)];
//    [editBtn addTarget:self action:@selector(editBtnClick) forControlEvents:UIControlEventTouchUpInside];
//    [editBtn setTitle:@"编辑" forState:UIControlStateNormal];
//    [editBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:editBtn];
//    self.navigationItem.rightBarButtonItem = rightItem;
//    editBtn.hidden = YES;
//    _mainTableView.userInteractionEnabled = YES;
}

// 点击编辑按钮
//- (void)editBtnClick {
//    _mainTableView.userInteractionEnabled = !_mainTableView.userInteractionEnabled;
//}


- (void)yiQiShowNetWorking {
    NSLog(@"刷新");
}


#pragma mark - 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
    
}

// 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 90;
    } else if (indexPath.section == 1) {
        return 65;
    }else {
        return 50;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else if (section == 1) {
        return 4;
    }else {
        return 1;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10*ysIZE;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 头像cell
    if (indexPath.section == 0) {
        LZPersonInfoTopCell *topCell = [tableView dequeueReusableCellWithIdentifier:cellIDa];
        
        if (!userInfo.userIcon || [userInfo.userIcon isEqualToString:@""]) {
            topCell.iconImageView.image = [UIImage imageNamed:@"icon_center_tx"];
        }else {
            [topCell.iconImageView sd_setImageWithURL:[NSURL URLWithString:userInfo.userIcon] placeholderImage:[UIImage imageNamed:@"icon_center_tx"]];
        }
        
    //topCell.iconImageView.image = userInfo.userIcon ? userInfo.userIcon : [UIImage imageNamed:@"icon_center_tx"];
        return topCell;
        // 中间cell
    } else if (indexPath.section == 1) {
        LZPersonInfoMidCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIDb];
        cell.textLabel.text = _titleArray[indexPath.row];
        cell.contentLabel.text = _firstDataArr[indexPath.row];
        return cell;
        
    }else {
        // 修改密码cell
        LZPersonInfoBottomCell *bottomCell = [[LZPersonInfoBottomCell alloc] init];
        bottomCell = [tableView dequeueReusableCellWithIdentifier:cellIDc];
        if (!bottomCell) {
            bottomCell = [[LZPersonInfoBottomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIDc];
        }
        return bottomCell;
    }
}

// 点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section) {
        case 0:{
            // 头像
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            [window addSubview:self.selectView];
        }
            break;
        case 1:
            if (indexPath.row == 0) {
                //修改名字
                [self changItemWithName:@"修改姓名" indexPath:[NSIndexPath indexPathForRow:0 inSection:1] keyBoradType:UIKeyboardTypeDefault cellType:CellTypeWithDefualt];
                
            }else if (indexPath.row == 1) {
                // 性别
                UIWindow *window = [UIApplication sharedApplication].keyWindow;
                [window addSubview:self.selectSexView];
                
            }else if (indexPath.row == 2) {
                //修改年龄
                [self changItemWithName:@"修改年龄" indexPath:[NSIndexPath indexPathForRow:2 inSection:1] keyBoradType:UIKeyboardTypeNumberPad cellType:CellTypeWithAge];
            }else {
                //修改手机号码
                [self changItemWithName:@"请输入密码" indexPath:[NSIndexPath indexPathForRow:3 inSection:1] keyBoradType:UIKeyboardTypeURL cellType:CellTypeWithDefualt];
                
            }
            break;
        case 2:{
            LZChangPwdViewController *changPwdVC = [[LZChangPwdViewController alloc] init];
            [self.navigationController pushViewController:changPwdVC animated:YES];
        }
            break;
            
        default:
            break;
    }
}

// 选择头像代理方法
-(void)SelectCellIndexPath:(NSInteger)cellSection index:(NSInteger)cellIndex {
    if (cellSection == 0 && cellIndex == 0) {
        NSLog(@"点击相册");
        [JTTakeAlbumOrCamera takeAlbumWithViewcontroller:self withID:self];
        [_selectView removeFromSuperview];
        
    }else if (cellSection == 0 && cellIndex == 1) {
        NSLog(@"点击相机");
        [JTTakeAlbumOrCamera takeCameraWithViewcontroller:self withID:self];
        [_selectView removeFromSuperview];
    }else {
        NSLog(@"点击取消");
        [self.selectView removeFromSuperview];
    }
}

// 选择性别代理方法
-(void)selectSEX:(NSString *)sex cellIndex:(NSInteger)cellIndex {
    if (cellIndex == 1) {
        [_selectSexView removeFromSuperview];
        return;
    }else {
        [self requestWithSex:sex];
        userInfo.userSex = sex;
        [LZUserInfo saveUserInfo:userInfo];
        
        [_contentArray replaceObjectAtIndex:1 withObject:sex];
        [_selectSexView removeFromSuperview];
//        _firstArr[1] = sex;
        // 刷新
        
//        LZPersonInfoMidCell *cell = [self.mainTableView cellForRowAtIndexPath:indexPath];
//        cell.contentLabel.text = userInfo.userSex;
        [_firstDataArr replaceObjectAtIndex:1 withObject:sex];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:1];
        [self.mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        
        //[self.mainTableView reloadData];
    }
}

// 选中照片回调方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    // UIImagePickerControllerOriginalImage 原始图片
    // UIImagePickerControllerEditedImage 编辑后图片
    UIImage *icon = info[UIImagePickerControllerEditedImage];
    //[self saveImage:icon withName:@"currentImage.png"];
    
    // 换头像以后网络请求
    [self requestWithIcon:icon];
    [picker dismissViewControllerAnimated:YES completion:NULL];
    
}

#pragma mark - 保存图片至本地沙盒
//- (void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName
//{
//    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.8);
//    // 获取沙盒目录
//    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
//    // 将图片写入文件
//    [imageData writeToFile:fullPath atomically:NO];
//}


// 选择头像View
-(LZSelectView *)selectView {
    if (_selectView) {
        return _selectView;
    }
    _selectView = [[LZSelectView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_Width, SCREEN_Height)];
    _selectView.pointDeleGate = self;
    return _selectView;
}

// 选择性别View
-(LZSelectSexView *)selectSexView {
    if (_selectSexView) {
        return _selectSexView;
    }
    _selectSexView = [[LZSelectSexView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_Width, SCREEN_Height)];
    _selectSexView.pointDeleGate = self;
    return _selectSexView;
}

// 修改年龄名字方法
- (void)changItemWithName:(NSString *)itemName indexPath:(NSIndexPath *)indexPath keyBoradType:(UIKeyboardType)type cellType:(CellType)cellType {
    LPopChangView *changeView = [[LPopChangView alloc] initWithFrame:self.navigationController.view.bounds AndTitle:[NSString stringWithFormat:@"%@",itemName] type:type];
    [self.navigationController.view addSubview:changeView];
    
    __weak typeof(changeView) weakChangeView = changeView;
    indexPath.row == 3 ? changeView.textField.secureTextEntry = YES : NO;
    changeView.InputContentBlock = ^(NSString *inputContent){
        if (!inputContent.length) {
            [YJProgressHUD showMessage:@"输入不能为空" inView:self
             .navigationController.view];
            return;
        }
        
        switch (indexPath.row) {
            case 0:// 姓名
                if (inputContent.length > 8) {
                    [YJProgressHUD showMessage:@"名字长度最多八位" inView:self.navigationController.view];
                    return;
                }
                [self requestWithName:inputContent];
                userInfo.userName = inputContent;
                [LZUserInfo saveUserInfo:userInfo];
                
                break;
            case 1: // 性别
//                userInfo.userSex = inputContent;
//                [LZUserInfo saveUserInfo:userInfo];
                break;
            case 2:// 年龄
                [self requestWithAge:inputContent];
                userInfo.userAge = inputContent;
                [LZUserInfo saveUserInfo:userInfo];
                NSInteger age = [inputContent intValue];
                if (age <= 0 || age >= 100) {
                    [YJProgressHUD showMessage:@"年龄输入有误" inView:self.navigationController.view];
                    return;
                }
                break;
            case 3:// 手机号
                if (![inputContent isEqualToString:userInfo.passWord]) {
                    [YJProgressHUD showMessage:@"密码输入错误" inView:weakChangeView];
                    return;
                }else {
                    LZChangPhoneVC *changPhoneVC = [[LZChangPhoneVC alloc] init];
                    [self.navigationController pushViewController:changPhoneVC animated:YES];
                    // block回传电话号码
                    changPhoneVC.returnTelBlock = ^(NSString *tel){
                    _firstDataArr[3] = tel;
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:1];
                        [self.mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                    };
                }
                break;
                
            default:
                break;
        }
        // 如果是手机号的cell不赋值
        if (indexPath.row != 3) {
            _firstDataArr[indexPath.row] = inputContent;
            [self.mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        }
        [weakChangeView removeFromSuperview];
    };
}

// 修改头像
- (void)requestWithIcon:(UIImage *)icon {
    NSDictionary *paramas = @{@"uid": userInfo.uid};
    NSMutableDictionary *dict1 = [NSMutableDictionary dictionaryWithObject:icon forKey:@"pic"];
    
    [BaseRequest requestWithMethodForFile:TestURL paramars:paramas paramarsSite:@"Personage/editInfo" fileDict:dict1 progressBlock:nil successBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"修改头像失败" inView:self.view];
        }else if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"修改头像成功" inView:self.view];
            
            // 拿到新换的照片转存为字符串
            NSString * pic = dict[@"pic"];
            NSString *iconStr = [NSString stringWithFormat:@"%@%@",IconURL,pic];
            userInfo.userIcon = iconStr;
            [LZUserInfo saveUserInfo:userInfo];
            //    self.selectImage = [LZUserInfo shareInfo].usericon;
            [self.mainTableView reloadData];
            ;
        }
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"修改失败" inView:self.view];
    }];
    
}
// 修改姓名
- (void)requestWithName:(NSString *)name {
    NSString * stringName = [name stringByReplacingOccurrencesOfString:@"\"" withString:@"”" ];
    
    NSDictionary *paramas = @{@"uid": userInfo.uid,@"name":stringName};
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"Personage/editInfo" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"修改名字失败" inView:self.view];
        }else if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"修改名字成功" inView:self.view];
        }
        
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"修改失败" inView:self.view];
    }];
}

// 修改性别
- (void)requestWithSex:(NSString *)sex {
    
    NSDictionary *paramas = @{@"uid": userInfo.uid,@"sex":sex};
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"Personage/editInfo" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"修改性别失败" inView:self.view];
        }else if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"修改性别成功" inView:self.view];
        }
        
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"修改失败" inView:self.view];
    }];
}

// 修改年龄
- (void)requestWithAge:(NSString *)age {
    
    NSDictionary *paramas = @{@"uid": userInfo.uid,@"age":age};
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"Personage/editInfo" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"修改年龄失败" inView:self.view];
        }else if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"修改年龄成功！" inView:self.view];
        }
        
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"修改失败" inView:self.view];
    }];
}





@end
